package sg.edu.nus.comp.icreate.ivletalk.utils.net;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.xmlpull.v1.XmlPullParserException;

import sg.edu.nus.comp.icreate.ivletalk.utils.xml.XmlParser;
import android.os.AsyncTask;
import android.util.Log;

/**
 * @author j This is the class to pull data from IVLE. This class will connect
 *         to the url given by {@link DataPuller#execute(String...)}.
 * 
 *         User should execute the connection by
 *         {@link DataPuller#execute(String...)} and get the data by
 *         {@link DataPuller#get()}.
 * 
 *         User should pass in an {@link XmlParser}. An example of using is in
 *         {@link sg.edu.nus.comp.icreate.ivletalk.module.MainActivity}.
 */
public class DataPuller extends AsyncTask<String, Void, Object> {

	private Exception exception;
	private XmlParser parser;

	public DataPuller(XmlParser parser) {
		super();
		this.parser = parser;
	}

	@Override
	protected Object doInBackground(String... url) {
		HttpURLConnection urlConnection;
		try {
			urlConnection = (HttpURLConnection) new URL(url[0]).openConnection();
			InputStream in = new BufferedInputStream(urlConnection.getInputStream());
			return parseData(in);
		} catch (Exception e) {
			this.exception = e;
			return null;
		}
	}

	protected void onPostExecute(InputStream in) {
		if (this.exception != null)
			Log.e("err", "err", this.exception);
	}

	protected Object parseData(InputStream in) {
		try {
			parser.setInput(in);
			return parser.getResult();
		} catch (XmlPullParserException e) {
			return null;
		}
	}

}